import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
// import 'package:moonmate/services/app_state_notifier.dart'; // 未使用，注释掉
import 'package:moonmate/services/interaction_service.dart';
import 'package:moonmate/utils/error_handler.dart';
// AppError and AppErrorType imports removed as per requirements

/// 用户体验服务，负责管理应用流程和用户体验优化
class UserExperienceService {
  // 单例模式
  static final UserExperienceService _instance = UserExperienceService._internal();
  factory UserExperienceService() => _instance;
  
  // 私有构造函数
  UserExperienceService._internal();
  
  // 状态通知器，改为可选字段
  // AppStateNotifier? _appStateNotifier; // 未使用，注释掉

  
  // 导航历史栈
  final List<String> _navigationHistory = [];
  
  // 当前流程状态
  FlowState _currentFlowState = FlowState.normal;
  
  // 是否正在执行流程
  bool _isFlowRunning = false;
  
  // 上次导航时间，用于节流
  DateTime? _lastNavigationTime;
  
  // 初始化应用流程
  Future<void> initializeFlow(BuildContext context) async {
    try {
      // 移除对AppStateNotifier.instance的引用
      // 默认设置为普通状态
      _currentFlowState = FlowState.normal;
    } catch (e) {
      ErrorHandler().handleError(e, 'InitializeFlow');
      _currentFlowState = FlowState.normal;
    }
  }
  
  // 安全导航到指定页面，防止重复导航
  Future<bool> safeNavigate(
    BuildContext context,
    Widget page,
    {String? routeName,
    bool replace = false,
    bool clearHistory = false,
    Duration minInterval = const Duration(milliseconds: 300),
    Object? arguments}
  ) async {
    // 导航节流，防止快速重复导航
    final now = DateTime.now();
    if (_lastNavigationTime != null &&
        now.difference(_lastNavigationTime!).inMilliseconds < minInterval.inMilliseconds) {
      return false;
    }
    
    _lastNavigationTime = now;
    
    try {
      // 确保在正确的上下文状态下导航
      if (!context.mounted) return false;
      
      // 记录导航历史
      if (routeName != null && !replace) {
        _navigationHistory.add(routeName);
        if (_navigationHistory.length > 50) {
          _navigationHistory.removeAt(0); // 限制历史记录长度
        }
      }
      
      if (clearHistory) {
        _navigationHistory.clear();
        
        // 清空导航栈，直接跳转到指定页面
        if (context.mounted) {
          await Navigator.pushAndRemoveUntil(
            context,
            MaterialPageRoute(builder: (context) => page),
            (route) => false,
          );
        }
      } else if (replace) {
        // 替换当前页面
        if (context.mounted) {
          await Navigator.pushReplacement(
            context,
            MaterialPageRoute(builder: (context) => page, settings: RouteSettings(name: routeName)),
          );
        }
      } else {
        // 正常导航到新页面
        if (context.mounted) {
          await Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => page, settings: RouteSettings(name: routeName)),
          );
        }
      }
      
      return true;
    } catch (e) {
      ErrorHandler().handleError(e, 'SafeNavigate');
      return false;
    }
  }
  
  // 返回上一页
  bool navigateBack(BuildContext context, {Object? result}) {
    try {
      if (_navigationHistory.isNotEmpty) {
        _navigationHistory.removeLast();
      }
      
      if (Navigator.canPop(context)) {
        Navigator.pop(context, result);
        return true;
      }
      return false;
    } catch (e) {
      ErrorHandler().handleError(e, 'NavigateBack');
      return false;
    }
  }
  
  // 执行一系列流程步骤
  Future<bool> executeFlow(
    BuildContext context,
    List<FlowStep> steps,
    {void Function(int stepIndex)? onStepComplete,
    void Function()? onFlowStart,
    void Function()? onFlowComplete,
    void Function(dynamic error)? onFlowError}
  ) async {
    if (_isFlowRunning) {
      // 已经有流程在运行，防止重叠
      return false;
    }
    
    _isFlowRunning = true;
    _currentFlowState = FlowState.customFlow;
    
    try {
      // 流程开始回调
      onFlowStart?.call();
      
      // 按顺序执行每一步
      for (int i = 0; i < steps.length; i++) {
        final step = steps[i];
        
        try {
          // 执行步骤
          final success = await _executeFlowStep(context, step);
          
          if (step.isRequired && !success) {
            // 必需步骤失败，终止整个流程
            throw Exception('流程步骤 ${i + 1} 失败');
          }
          
          // 步骤完成回调
          onStepComplete?.call(i);
          
          // 如果当前步骤不是最后一步，添加步骤间延迟
          if (i < steps.length - 1 && step.delayBeforeNext > Duration.zero) {
            await Future.delayed(step.delayBeforeNext);
          }
        } catch (e) {
          ErrorHandler().handleError(e, 'FlowStep $i');
          onFlowError?.call(Exception('流程步骤 $i 出错: $e'));
          
          if (step.isRequired) {
            throw Exception('流程步骤执行失败');
          }
        }
      }
      
      // 流程完成回调
      onFlowComplete?.call();
      return true;
    } catch (e) {
      ErrorHandler().handleError(e, 'ExecuteFlow');
      onFlowError?.call(Exception('流程执行失败: $e'));
      return false;
    } finally {
      _isFlowRunning = false;
      _currentFlowState = FlowState.normal;
    }
  }
  
  // 执行单个流程步骤
  Future<bool> _executeFlowStep(BuildContext context, FlowStep step) async {
    switch (step.type) {
      case FlowStepType.navigation:
        // 导航步骤
        if (step.page != null) {
          return await safeNavigate(
            context,
            step.page!,
            routeName: step.routeName,
            replace: step.replace,
          );
        }
        break;
        
      case FlowStepType.action:
        // 执行操作步骤
        if (step.action != null) {
          final result = await InteractionService().handleAsyncOperation(
            context,
            step.action!,
            loadingMessage: step.loadingMessage,
            successMessage: step.successMessage,
            showSuccessMessage: step.showSuccessMessage,
            showLoading: step.showLoading,
          );
          return result != null;
        }
        break;
        
      case FlowStepType.wait:
        // 等待步骤
        await Future.delayed(step.duration ?? const Duration(milliseconds: 500));
        return true;
        
      case FlowStepType.condition:
        // 条件判断步骤
        if (step.condition != null) {
          final conditionMet = await step.condition!();
          
          // 根据条件选择执行路径
          if (conditionMet) {
            return step.onConditionMet != null ? await _executeFlowStep(context, step.onConditionMet!) : true;
          } else {
            return step.onConditionFailed != null ? await _executeFlowStep(context, step.onConditionFailed!) : true;
          }
        }
        break;
    }
    
    return false;
  }
  
  // 显示操作成功后的流程总结
  void showOperationSummary(BuildContext context, {
    required String title,
    required String message,
    String? confirmText,
    VoidCallback? onConfirm,
    bool showConfirmButton = true,
  }) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(title),
          content: Text(message),
          actions: <Widget>[
            if (showConfirmButton)
              TextButton(
                child: Text(confirmText ?? '确定'),
                onPressed: () {
                  Navigator.of(context).pop();
                  onConfirm?.call();
                },
              ),
          ],
        );
      },
    );
  }
  
  // 显示教程或引导
  void showFeatureTutorial(
    BuildContext context,
    List<TutorialStep> steps,
    {void Function()? onComplete}
  ) {
    // 可以实现引导层、高亮提示等功能
    // 这里简单实现为连续显示对话框
    int currentStep = 0;
    
    void showNextStep() {
      if (currentStep < steps.length) {
        final step = steps[currentStep];
        
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text(step.title),
              content: Text(step.description),
              actions: <Widget>[
                if (currentStep < steps.length - 1)
                  TextButton(
                    child: const Text('下一步'),
                    onPressed: () {
                      Navigator.of(context).pop();
                      currentStep++;
                      showNextStep();
                    },
                  ),
                if (currentStep == steps.length - 1)
                  TextButton(
                    child: const Text('完成'),
                    onPressed: () {
                      Navigator.of(context).pop();
                      onComplete?.call();
                    },
                  ),
              ],
            );
          },
        );
      }
    }
    
    showNextStep();
  }
  
  // 平滑滚动到指定位置
  void smoothScrollTo(
    ScrollController controller,
    double position,
    {Duration duration = const Duration(milliseconds: 300),
    Curve curve = Curves.easeInOut}
  ) {
    controller.animateTo(
      position,
      duration: duration,
      curve: curve,
    );
  }
  
  // 自动滚动到底部
  void scrollToBottom(
    ScrollController controller,
    {Duration duration = const Duration(milliseconds: 300)}
  ) {
    smoothScrollTo(
      controller,
      controller.position.maxScrollExtent,
      duration: duration,
    );
  }
  
  // 自动滚动到顶部
  void scrollToTop(
    ScrollController controller,
    {Duration duration = const Duration(milliseconds: 300)}
  ) {
    smoothScrollTo(
      controller,
      0,
      duration: duration,
    );
  }
  
  // 延迟执行任务，确保在当前帧渲染完成后执行
  void scheduleTask(VoidCallback task) {
    SchedulerBinding.instance.addPostFrameCallback((_) {
      task();
    });
  }
  
  // 获取当前流程状态
  FlowState get currentFlowState => _currentFlowState;
  
  // 获取导航历史
  List<String> get navigationHistory => List.unmodifiable(_navigationHistory);
  
  // 清理资源
  void dispose() {
    _navigationHistory.clear();
  }
}

/// 流程状态枚举
enum FlowState {
  normal,
  firstLaunch,
  profileSetup,
  customFlow,
  onboarding,
}

/// 流程步骤类型枚举
enum FlowStepType {
  navigation,
  action,
  wait,
  condition,
}

/// 流程步骤类
class FlowStep {
  final FlowStepType type;
  final Widget? page;
  final String? routeName;
  final bool replace;
  final Future<dynamic> Function()? action;
  final Future<bool> Function()? condition;
  final FlowStep? onConditionMet;
  final FlowStep? onConditionFailed;
  final Duration? duration;
  final String loadingMessage;
  final String successMessage;
  final bool showLoading;
  final bool showSuccessMessage;
  final Duration delayBeforeNext;
  final bool isRequired;
  
  const FlowStep._({
    required this.type,
    this.page,
    this.routeName,
    this.replace = false,
    this.action,
    this.condition,
    this.onConditionMet,
    this.onConditionFailed,
    this.duration,
    this.loadingMessage = '处理中...',
    this.successMessage = '',
    this.showLoading = true,
    this.showSuccessMessage = true,
    this.delayBeforeNext = Duration.zero,
    this.isRequired = true,
  });
  
  // 创建导航步骤
  factory FlowStep.navigate(
    Widget page,
    {String? routeName,
    bool replace = false,
    bool isRequired = true,
    Duration delayBeforeNext = Duration.zero}
  ) {
    return FlowStep._(
      type: FlowStepType.navigation,
      page: page,
      routeName: routeName,
      replace: replace,
      isRequired: isRequired,
      delayBeforeNext: delayBeforeNext,
    );
  }
  
  // 创建操作步骤
  factory FlowStep.action(
    Future<dynamic> Function() action,
    {String loadingMessage = '处理中...',
    String successMessage = '操作成功',
    bool showLoading = true,
    bool showSuccessMessage = true,
    bool isRequired = true,
    Duration delayBeforeNext = Duration.zero}
  ) {
    return FlowStep._(
      type: FlowStepType.action,
      action: action,
      loadingMessage: loadingMessage,
      successMessage: successMessage,
      showLoading: showLoading,
      showSuccessMessage: showSuccessMessage,
      isRequired: isRequired,
      delayBeforeNext: delayBeforeNext,
    );
  }
  
  // 创建等待步骤
  factory FlowStep.wait(
    Duration duration,
    {bool isRequired = true}
  ) {
    return FlowStep._(
      type: FlowStepType.wait,
      duration: duration,
      isRequired: isRequired,
    );
  }
  
  // 创建条件判断步骤
  factory FlowStep.condition(
    Future<bool> Function() condition,
    {FlowStep? onConditionMet,
    FlowStep? onConditionFailed,
    bool isRequired = true}
  ) {
    return FlowStep._(
      type: FlowStepType.condition,
      condition: condition,
      onConditionMet: onConditionMet,
      onConditionFailed: onConditionFailed,
      isRequired: isRequired,
    );
  }
}

/// 教程步骤类
class TutorialStep {
  final String title;
  final String description;
  final String? imagePath;
  final Widget? customContent;
  
  const TutorialStep({
    required this.title,
    required this.description,
    this.imagePath,
    this.customContent,
  });
}

// 扩展BuildContext以方便使用导航功能
extension BuildContextNavigation on BuildContext {
  // 安全导航
  Future<bool> navigateTo(Widget page, {String? routeName}) {
    return UserExperienceService().safeNavigate(this, page, routeName: routeName);
  }
  
  // 安全替换当前页面
  Future<bool> replaceWith(Widget page, {String? routeName}) {
    return UserExperienceService().safeNavigate(this, page, routeName: routeName, replace: true);
  }
  
  // 清空导航栈并导航
  Future<bool> navigateAndClear(Widget page, {String? routeName}) {
    return UserExperienceService().safeNavigate(this, page, routeName: routeName, clearHistory: true);
  }
  
  // 返回上一页
  bool goBack({Object? result}) {
    return UserExperienceService().navigateBack(this, result: result);
  }
  
  // 显示操作总结
  void showOperationSummary({
    required String title,
    required String message,
    String? confirmText,
    VoidCallback? onConfirm,
  }) {
    UserExperienceService().showOperationSummary(
      this,
      title: title,
      message: message,
      confirmText: confirmText,
      onConfirm: onConfirm,
    );
  }
}
